#target illustrator
(function () {
    if (app.documents.length === 0) { alert("请先打开一个文档。"); return; }
    var doc = app.activeDocument;

    // ===== 命令缓存（首次探测成功后记住可用别名） =====
    var CMD_CACHE = {};
    function execCmd(key, aliases) {
        if (CMD_CACHE[key]) { app.executeMenuCommand(CMD_CACHE[key]); return true; }
        for (var i = 0; i < aliases.length; i++) {
            try { app.executeMenuCommand(aliases[i]); CMD_CACHE[key] = aliases[i]; return true; } catch(e){}
        }
        return false;
    }
    var CMD = {
        release:       { key: "release",       aliases: ["releaseMask","releaseClippingMask","clip-masking"] },
        makeMask:      { key: "makeMask",      aliases: ["makeMask","Make Mask"] },
        selectInAB:    { key: "selectInAB",    aliases: ["selectallinartboard"] },
        inverse:       { key: "inverse",       aliases: ["Inverse","inverse","Selection Inverse","Inverse menu item"] },
        clear:         { key: "clear",         aliases: ["clear","Delete","cut"] },
        selectAll:     { key: "selectAll",     aliases: ["selectall"] },
        bringToFront:  { key: "bringToFront",  aliases: ["sendToFront"] },
        // 降重绘相关
        togglePreview: { key: "togglePreview", aliases: ["preview","Preview"] },           // 轮廓/预览
        toggleEdges:   { key: "toggleEdges",   aliases: ["showEdges"] },                   // 选区边
        toggleBBox:    { key: "toggleBBox",    aliases: ["toggleBoundingBox"] },           // 边框
        toggleSmart:   { key: "toggleSmart",   aliases: ["smartGuides"] }                  // 智能参考线
    };
    function tryCmd(desc){ return execCmd(desc.key, desc.aliases); }

    // ===== 降重绘：进入/退出（尽力减少可见闪动） =====
    function enterNoRedraw() {
        var s = { ui: app.userInteractionLevel, didPreview:false, didEdges:false, didBBox:false, didSmart:false };
        try { app.userInteractionLevel = UserInteractionLevel.DONTDISPLAYALERTS; } catch(e){}
        try { if (tryCmd(CMD.togglePreview)) s.didPreview = true; } catch(e){}
        try { if (tryCmd(CMD.toggleEdges))   s.didEdges   = true; } catch(e){}
        try { if (tryCmd(CMD.toggleBBox))    s.didBBox    = true; } catch(e){}
        try { if (tryCmd(CMD.toggleSmart))   s.didSmart   = true; } catch(e){}
        return s;
    }
    function exitNoRedraw(s) {
        try { if (s.didSmart)   tryCmd(CMD.toggleSmart); } catch(e){}
        try { if (s.didBBox)    tryCmd(CMD.toggleBBox);  } catch(e){}
        try { if (s.didEdges)   tryCmd(CMD.toggleEdges); } catch(e){}
        try { if (s.didPreview) tryCmd(CMD.togglePreview); } catch(e){}
        try { if (s.ui != null) app.userInteractionLevel = s.ui; } catch(e){}
        try { app.redraw(); } catch(e){}
    }

    // ===== 工具函数（尽量避免遍历，局部查找） =====
    function nearestClippingGroup(it){
        while (it && it.parent){ if (it.typename==="GroupItem" && it.clipped) return it; it = it.parent; }
        return null;
    }
    function findClipShape(group){
        for (var i=0;i<group.pathItems.length;i++) if (group.pathItems[i].clipping) return group.pathItems[i];
        for (var j=0;j<group.compoundPathItems.length;j++){
            var c = group.compoundPathItems[j];
            for (var k=0;k<c.pathItems.length;k++) if (c.pathItems[k].clipping) return c;
        }
        // 仅下探一层
        for (var g=0; g<group.groupItems.length; g++){
            var sub = group.groupItems[g];
            for (var i2=0;i2<sub.pathItems.length;i2++) if (sub.pathItems[i2].clipping) return sub.pathItems[i2];
            for (var j2=0;j2<sub.compoundPathItems.length;j2++){
                var c2=sub.compoundPathItems[j2];
                for (var k2=0;k2<c2.pathItems.length;k2++) if (c2.pathItems[k2].clipping) return c2;
            }
        }
        return null;
    }

    var LAYER_SEQ = 1;
    function makeLayerName(base){
        if (!base||base==="") base="ClippingGroup";
        return base + "_" + (LAYER_SEQ++); // 自增，避免 O(N) 重名扫描
    }

    // 统一锁层策略
    function snapshotLayerStates(document){
        var s=[], layers=document.layers;
        for (var i=0;i<layers.length;i++){ s.push({ layer: layers[i], locked: layers[i].locked, visible: layers[i].visible }); }
        return s;
    }
    function lockAllLayers(document){
        for (var i=0;i<document.layers.length;i++){ try{ document.layers[i].locked = true; }catch(e){} }
    }
    function restoreLayerStates(states){
        for (var i=0;i<states.length;i++){
            try{ states[i].layer.locked  = states[i].locked; }catch(e){}
            try{ states[i].layer.visible = states[i].visible; }catch(e){}
        }
    }

    // 单个剪切组完整流程（该组已在独立图层）
    function processOneClippingGroup(clipGroup){
        if (!clipGroup) throw "空的剪切组。";
        var clipShape = findClipShape(clipGroup);
        if (!clipShape) throw "未找到剪切蒙版形状。";

        // 以剪切形状边界建临时画板
        var gb = clipShape.geometricBounds; // [L, T, R, B]
        var left = Math.min(gb[0], gb[2]),  top = Math.max(gb[1], gb[3]);
        var right= Math.max(gb[0], gb[2]),  bottom = Math.min(gb[1], gb[3]);
        if (!(isFinite(left)&&isFinite(top)&&isFinite(right)&&isFinite(bottom))) throw "几何边界非法。";
        if (right<=left || top<=bottom) throw "剪切边界宽高为 0。";

        var prevABIndex = doc.artboards.getActiveArtboardIndex();
        var tempAB = doc.artboards.add([left, top, right, bottom]);
        var tempIdx = doc.artboards.length - 1;
        try { tempAB.name = "From_Clipping_Mask_TEMP"; } catch(e){}
        doc.artboards.setActiveArtboardIndex(tempIdx);

        var targetLayer = clipGroup.layer;

        // 释放剪切蒙版
        doc.selection = null; clipGroup.selected = true;
        execCmd(CMD.release.key, CMD.release.aliases);

        // 选中活动画板内对象（优先内建）
        doc.selection = null;
        var ok=false; try{ ok = doc.selectObjectsOnActiveArtboard(); }catch(e){}
        if (!ok) execCmd(CMD.selectInAB.key, CMD.selectInAB.aliases);

        // 反选并删除（只作用于当前解锁层）
        if (doc.selection && doc.selection.length>0) {
            if (execCmd(CMD.inverse.key, CMD.inverse.aliases)) {
                execCmd(CMD.clear.key, CMD.clear.aliases);
            }
        }

        // 重新建立剪切蒙版
        doc.selection = null;
        execCmd(CMD.selectAll.key, CMD.selectAll.aliases); // 仅选当前层
        try { clipShape.selected = true; } catch(e){}
        try {
            if (clipShape.zOrder) clipShape.zOrder(ZOrderMethod.BRINGTOFRONT);
            else execCmd(CMD.bringToFront.key, CMD.bringToFront.aliases);
        } catch(e){}
        if (!execCmd(CMD.makeMask.key, CMD.makeMask.aliases)) throw "未能创建剪切蒙版。";

        // 删除临时画板 & 恢复原活动画板
        try { doc.artboards.setActiveArtboardIndex(prevABIndex); } catch(e){}
        try { doc.artboards.remove(tempIdx); }
        catch(e2){
            try { for (var i=doc.artboards.length-1;i>=0;i--) { if (doc.artboards[i].name==="From_Clipping_Mask_TEMP"){ doc.artboards.remove(i); break; } } } catch(e3){}
        }
    }

    // ===== 主流程（一次性撤销）：多选 → 移新图层 → 统一锁层 → 逐个处理 → 还原 =====
    var uiState = enterNoRedraw();
    try {
        if (!doc.selection || doc.selection.length===0) throw "请选中一个或多个剪切组，或其内部对象。";

        // 收集唯一剪切组
        var sel = [], groups=[];
        for (var i=0;i<doc.selection.length;i++) sel.push(doc.selection[i]);
        function addUnique(g){ for (var i=0;i<groups.length;i++) if (groups[i]===g) return; groups.push(g); }
        for (var k=0;k<sel.length;k++){
            var node = sel[k]; if (!node || node.locked || node.hidden) continue;
            var g = (node.typename==="GroupItem" && node.clipped) ? node : nearestClippingGroup(node);
            if (g) addUnique(g);
        }
        if (groups.length===0) throw "未在所选对象中找到剪切组（GroupItem.clipped==true）。";

        // 各自移入新图层（命名自增，避免全局扫描）
        for (var j=0;j<groups.length;j++){
            var cg = groups[j];
            var base = (function(){
                try{ if (cg.name && cg.name!=="") return "CG_"+cg.name; }catch(e){}
                try{ if (cg.layer && cg.layer.name) return "CG_from_"+cg.layer.name; }catch(e2){}
                return "ClippingGroup";
            })();
            var newLayer = doc.layers.add();
            try { newLayer.name = makeLayerName(base); } catch(e){}
            try { newLayer.locked=false; newLayer.visible=true; } catch(e){}
            try { cg.locked=false; cg.hidden=false; } catch(e){}
            cg.move(newLayer, ElementPlacement.PLACEATBEGINNING);
        }

        // 统一锁层：一次快照 → 全锁 → 每次只解锁目标层 → 处理 → 再锁回 → 最后一次性还原
        var snapshot = snapshotLayerStates(doc);
        for (var t=0;t<groups.length;t++) try{ groups[t].layer.visible = true; }catch(e){}
        lockAllLayers(doc);

        for (var n=0;n<groups.length;n++){
            var grp = groups[n];
            var lyr = grp.layer;
            try { lyr.locked = false; doc.activeLayer = lyr; } catch(e){}
            try { processOneClippingGroup(grp); } catch(e){ /* 可收集日志 */ }
            try { lyr.locked = true; } catch(e){}
        }

        restoreLayerStates(snapshot);
        //（一次脚本执行=一次撤销步骤，无需任何历史包装）
    } catch (err) {
        alert("错误: " + err);
    } finally {
        exitNoRedraw(uiState);
    }
})();
